import { React } from "react";
import getAssetsFile from "@/utils/pub-use";
import { Image, Dialog, Input, Toast } from "antd-mobile";
import { useEffect, useState, react } from "react";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";
import * as echarts from "echarts";
import type { ComposeOption } from "echarts/core";
import type { TreeSeriesOption } from "echarts/charts";
import { DownFill } from "antd-mobile-icons";

import { checkNodeRelation, getCheckPwd } from "@/api/module/user";
import { EyeInvisibleOutline, EyeOutline } from "antd-mobile-icons";
import { useAppSelector } from "@/hooks/useAppSelector";
import "./Resettle.less";
const OperateComponent = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const userInfo = useAppSelector((state) => state.userInfo.userInfo);
  const assetsList = [
    {
      image: getAssetsFile("home/reward.png"),
      title: "reward",
      url: "/rewardRecord",
    },
    {
      image: getAssetsFile("home/invite.png"),
      title: "declaration",
      url: "/PlacementAccount",
    },
    {
      image: getAssetsFile("home/level.png"),
      title: "upgrade",
      url: "/upgrade",
    },
  ];
  const handleNavigation = (url) => {
    if (url === "/PlacementAccount") {
      if (userInfo.bind_status) {
        Toast.show({
          content: "您已报单，请前往升级",
        });
      } else {
        navigate(url); // 正常跳转
      }
    } else {
      navigate(url); // 其他页面正常跳转
    }
  };
  return (
    <div>
      <div className="flex items-center justify-between asstest mx-2 bg-bg-1 py-4 px-4 rounded-xl"></div>
      <div className="value text-white-1 py-6 px-4 bg-custom-gradient-1 rounded-xl relative -top-4 flex items-center justify-around">
        {assetsList.map((item) => {
          return (
            <div key={item.title} onClick={() => handleNavigation(item.url)}>
              <Image src={item.image} width={36} height={36} alt="" />
              <div className="text-xs text-center mt-2">{t(item.title)}</div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

const formatData = (data: {
  user_id: number;
  depth: number;
  button_user_id: string;
  can_bind: boolean;
  value?: number;
  name?: number;
  collapsed?: boolean;
  children: {
    user_id: number;
    depth: number;
    button_user_id: string;
    can_bind: boolean;
    value?: number;
    name?: number;
    children: {
      user_id: number;
      depth: number;
      button_user_id: string;
      can_bind: boolean;
      value?: number;
      name?: number;
    }[];
  }[];
}) => {
  if (!data) return;
  data["value"] = data.user_id;
  data["name"] = data.depth;
  data["collapsed"] = false;
  data.children?.map((item) => {
    // @ts-ignore
    formatData(item);
  });

  return data;
};
const MatrixDiagramComponent = () => {
  const navigate = useNavigate();
  const { t } = useTranslation();

  const [preNode, setPreNode] = useState<0 | string>();
  const [visible, setVisible] = useState(true); // 初始显示密码弹框
  const [password, setPassword] = useState(""); // 存储输入的密码
  const [showPassword, setShowPassword] = useState(false); // 控制密码是否可见
  const [enevt, setEnevt] = useState("");
  const [isAuthenticated, setIsAuthenticated] = useState(false); // 是否通过密码验证

  const option: ComposeOption<TreeSeriesOption> = {
    tooltip: {
      trigger: "item",
      triggerOn: "mousemove",
    },
    series: [
      {
        type: "tree",
        data: [],
        orient: "vertical",
        top: "30",
        bottom: "50",
        left: "0",
        right: "0",
        symbolSize: 7,
        edgeShape: "polyline",
        lineStyle: {},
        label: {
          verticalAlign: "middle",
          align: "center",
          fontSize: 16,
          padding: [10, 10, 10, 10],
          ellipsis: "truncate",
          color: "red",
          backgroundColor: "#E99434",
          distance: 0,
          formatter: function (v) {
            return `{a|${v.value}}\n{b|${v.data.level}}\n{c|${v.data.total_achievement}}`;
          },
          rich: {
            a: {
              color: "#fff",
              fontWeight: "bold",
              fontSize: 14,
              align: "center",
            },
            b: {
              color: "#fff",
              fontWeight: "bold",
              fontSize: 14,
              align: "center",
            },
            c: {
              color: "#fff",
              fontSize: 14,
              align: "center",
            },
          },
        },
        itemStyle: {
          borderColor: "#fff",
          color: "pink",
        },
        leaves: {
          label: {
            position: "bottom",
            verticalAlign: "middle",
          },
        },
        expandAndCollapse: true,
        animationDuration: 550,
        animationDurationUpdate: 750,
      },
    ],
  };

  const reqNodeRelation = async (id?: string) => {
    const res = await checkNodeRelation(id);
    const formattedData = formatData(res.data.list_data);
    if (formattedData && formattedData.children) {
      // @ts-ignore
      option.series[0].data = [formatData(res.data.list_data)];
      setPreNode(res.data.list_data.button_user_id);
      var myChart = echarts.init(document.getElementById("treemap-container"));
      myChart.setOption(option);

      myChart.on("click", function (enevt) {
        // @ts-ignore
        if (enevt.data?.button_user_id != 0) {
          setEnevt(enevt.value);
          setVisible(true);
        }
        // @ts-ignore无子
        if (enevt.data?.can_bind) {
          navigate("/placementAccount?id=" + enevt.value);
          return;
        }
      });
    } else {
      var myChart = echarts.init(document.getElementById("treemap-container"));
      myChart.clear();
    }
  };

  // 关闭弹框
  const closeDialog = () => {
    setVisible(false);
  };

  // 处理密码输入
  const handlePasswordChange = (value: string) => {
    setPassword(value);
  };

  // 处理确认按钮点击
  const handleConfirm = async () => {
    if (password) {
      const res = await getCheckPwd(password);
      if (res.code === 0) {
        Toast.show({
          content: res.msg,
          position: "top",
        });
        setIsAuthenticated(true); // 密码验证通过
        closeDialog(); // 关闭弹框
        reqNodeRelation(); // 加载矩阵图数据
      } else {
        Toast.show({
          content: res.msg,
          position: "top",
        });
      }
    } else {
      Toast.show({
        content: "请输入密码！",
        position: "top",
      });
    }
  };

  const previousNode = () => {
    if (preNode == 0) return;
    reqNodeRelation(preNode);
  };

  return (
    <div>
      <div className="title">{t("matrixDiagram")}</div>
      {isAuthenticated ? ( // 如果通过验证，显示矩阵图
        <>
          <div className="flex justify-center items-center my-4 rotate-180">
            <DownFill
              onClick={previousNode}
              width={24}
              height={24}
              color="#e99434"
            />
          </div>
          <div id="treemap-container" className="h-56"></div>
        </>
      ) : null}

      {/* 密码输入弹框 */}
      <Dialog
        visible={visible}
        content={
          <div>
            <Input
              placeholder="请输入密码"
              value={password}
              clearable
              onChange={handlePasswordChange}
              suffix={
                <div
                  onClick={() => setShowPassword(!showPassword)}
                  style={{ color: "#fff", border: "0px solid #999" }}
                >
                  {showPassword ? <EyeOutline /> : <EyeInvisibleOutline />}
                </div>
              }
            />
          </div>
        }
        actions={[
          [
            {
              key: "cancel",
              text: "取消",
              onClick: closeDialog,
              style: {
                color: "#fff",
                backgroundColor: "#666",
                border: "0px solid #999",
              },
            },
            {
              key: "confirm",
              text: "确认",
              onClick: handleConfirm,
              style: {
                color: "#fff",
                backgroundColor: "#333",
                border: "0px solid #999",
              },
            },
          ],
        ]}
        onClose={closeDialog}
        bodyStyle={{
          backgroundColor: "#242424",
          color: "#fff",
          border: "0px solid #555",
        }}
        maskStyle={{
          backgroundColor: "rgba(0, 0, 0, 0.7)",
          border: "0px solid #555",
        }}
        style={{
          color: "#fff",
          backgroundColor: "#333",
          border: "0px solid #555",
          position: "fixed",
          top: "50%",
          left: "50%",
          transform: "translate(-50%, -50%)",
          zIndex: 90000000,
        }}
        closeOnMaskClick
        // 通过 className 覆盖 adm-dialog-action-row 的样式
        className="custom-dialog"
      />
    </div>
  );
};

export default function Resettle() {
  const { t } = useTranslation();
  const [pageType, setPageType] = useState(1);
  const [value, setValue] = useState("");

  return (
    <div className="text-white-1 px-4">
      {pageType == 0 ? (
        <div>
          <div
            style={{ fontWeight: 550 }}
            className="title py-2 text-center font-semibold text-2xl"
          >
            {t("matrix")}
          </div>
          <div>2FA OPT</div>
          <Input
            style={{
              "--font-size": "14px",
            }}
            className="bg-bg-1 py-4 mt-3 px-3 rounded-lg "
            placeholder={`${t("enter")}`}
            value={value}
            onChange={(val) => {
              setValue(val);
            }}
          />
          <div
            onClick={() => setPageType(1)}
            className="mt-8 text-center bg-bg-16 py-4 rounded-lg"
          >
            {t("continue")}
          </div>
        </div>
      ) : (
        <div>
          <div
            style={{ fontWeight: 550 }}
            className="title py-2 text-center font-semibold text-2xl"
          >
            {t("aimatrix")}
          </div>
          <OperateComponent />
          <MatrixDiagramComponent />
        </div>
      )}
    </div>
  );
}
